package com.lin.linchatgpt.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.lin.linchatgpt.service.email.EmailService;
import com.lin.linchatgpt.utils.LinResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/6/21 9:08
 * @Description
 */
@RequestMapping("lin_chat/valid_code")
@RestController
@Slf4j
public class ValidCodeController {
    @Resource
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @GetMapping("image")
    public LinResult getValidCode() {
        // 利用 hutool 工具，生成验证码图片资源
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 5);
        // 获得生成的验证码字符
        String code = captcha.getCode();
        // 将验证码字符存入 redis 中
        UUID uuid = UUID.randomUUID();
        redisTemplate.opsForValue().set(uuid.toString(), code, 60 * 5, TimeUnit.SECONDS);
        // 将验证码图片的二进制数据写入【响应体 response 】
        return LinResult.success().data("item", captcha.getImageBase64Data()).data("uuid", uuid.toString());
    }

    /**
     * 验证邮箱地址
     *
     * @param token 验证token
     * @return 验证结果
     */
    @GetMapping("verifyEmail")
    public LinResult verifyEmail(@RequestParam("email") String email, @RequestParam("token") String token) {
        log.info("用户邮箱地址==>{};验证token->{}",email,token);
        // 验证邮箱
        return emailService.verifyEmail(email, token) ? LinResult.success().message("验证成功，请返回主页登录")
                : LinResult.error().message("验证失败，请重新验证");
    }
}
